package com.zyc.studentstudy.utils

import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
import timber.log.Timber

/**
 * Created by zhangyuncai on 2025/3/25.
 * 描述：平替ThreadPoolManager
 */
object GlobalDispatcher {
    // 共用后台线程池（类似传统线程池的复用）
    private val appScope = CoroutineScope(
        Dispatchers.IO +
                SupervisorJob() +
                CoroutineExceptionHandler { _, e ->
                    Timber.e("GlobalDispatcher error: $e")
                }
    )

    fun launchIO(block: suspend CoroutineScope.() -> Unit): Job {
        return appScope.launch { block() }
    }

    fun cancelAll() {
        appScope.coroutineContext.cancelChildren()
    }
}